package com.crc.luojian.resolver.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crc.luojian.annotation.RequestBody;
import com.crc.luojian.resolver.RequestResolver;
import com.crc.luojian.util.RequestParameterConverter;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.util.Objects;

/**
 * @program: luojian-springframework
 * @description:  解析RequestBody
 * @author: luojian58
 * @create: 2021-06-11 10:07
 */
public class RequestBodyResolver implements RequestResolver {
    @Override
    public boolean support(Parameter parameter) {
        return parameter.getAnnotation(RequestBody.class) != null;
    }

    @Override
    public Object resolveArgument(HttpServletRequest request, Parameter parameter) {
        Class<?> clazz = parameter.getType();
        Object object;
        try {
            if (parameter.isAnnotationPresent(RequestBody.class)) {
                object = clazz.newInstance();
                Field[] declaredFields = clazz.getDeclaredFields();
                for(Field field : declaredFields){
                    field.setAccessible(true);
                    BufferedReader bufferedReader = request.getReader();
                    final StringBuffer buffer = new StringBuffer(4096);
                    String line = "";
                    String message = new String();
                    while ((line = bufferedReader.readLine()) != null) {
                        message += line;
                    }
                    JSONObject jsonObject = JSON.parseObject(message);
                    Object value = request.getParameter(field.getName());
                    Object value2 = jsonObject.getString(field.getName());
                    Object value3 = Objects.isNull(value)? value2:value;
                    if(Objects.isNull(value3)) {
                        field.set(object, value);
                        continue;
                    }
                    RequestParameterConverter converter = new RequestParameterConverter();
                    value = converter.convert(field.getType(), value3);
                    field.set(object, value);
                }
                return object;
            }


        }catch (Exception e){
            e.printStackTrace();

        }
        return null;
    }
}
